﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace myCompiler {
    public partial class MainForm : Form {
        public MainForm() {
            InitializeComponent();
        }

        private void RunCode(object sender, KeyEventArgs e) {
            if (e.KeyCode == Keys.F5)
            {
                InitialCompilerWorker();
                string code = this.textBoxCode.Text.Trim();
                MemoryStream fileStream = new MemoryStream(Encoding.ASCII.GetBytes(code));
                Scanner scnr = new Scanner(fileStream);
                MyParser parser = new MyParser(scnr);
                parser.Parse();
                CompilerWorker.GetInstance().EmitCode();
            }
            ScrollMessageToBottom();
        }

        private void ScrollMessageToBottom() {
            this.textBoxMessage.SelectionStart = textBoxMessage.Text.Length;
            textBoxMessage.ScrollToCaret();

        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            
            LoadCode();
        }

        private void InitialCompilerWorker()
        {
            CompilerWorker.ClearInstance();
            CompilerWorker.InitializeInstance(this);
            AddMessage(String.Format("========{0}=========", DateTime.Now));
        }

        private void LoadCode()
        {
            var path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            FileInfo fileInfo = new FileInfo(path + "Code.txt");
            if (fileInfo.Exists)
            {
                TextReader tr = new StreamReader("Code.txt");
                this.textBoxCode.Text = tr.ReadToEnd();
                tr.Close();
            }
        }


        public void AddMessage(string message)
        {
            this.textBoxMessage.Text += message + "\r\n";
        }
    }
}
